setMatrix2list <- function(sets){
 setsList <- vector("list",length = dim(sets)[2])
 names(setsList) <- colnames(sets)
 for (set in colnames(sets)){
  setsList[[set]] <- rownames(sets)[sets[,set]]
 }
 return(setsList)
} 

list2setMatrix <- function(geneIDs,listData){
 A <- matrix(0,nrow = length(geneIDs),ncol = length(unique(names(listData))))
 rownames(A) <- geneIDs
 colnames(A) <- names(listData)

#for each list set numbers
 for (set in names(listData)){
  A[intersect(rownames(A),listData[[set]]),set] <- 1
 } 
 return(A)
} 

fac2mat <- function(f){
l <- attributes(f)
l <- l$levels
print(l)

M <- matrix(0,nrow=length(f),ncol=length(l))
colnames(M) <- l

for (lvl in l){
 M[f==lvl,lvl] <- 1
}

return(M)
}


keggTable <- function(a,symbolList,contrast,filename = "keggTable.txt"){
 #Write significant geens to a KEGG readable list
 sigGenes <- rownames(a)[a[,contrast] !=0]
 cols <- sigGenes
 cols[a[sigGenes,contrast] == 1] <- "red"
 cols[a[sigGenes,contrast] == -1] <- "green"
 print(cols)
 #print(sigGenes)
 #print(unlist(symbolList)[sigGenes])
 
 exportData <-data.frame(unlist(symbolList)[sigGenes], colour = cols)
 exportData <- exportData[!is.na(exportData[,"unlist.symbolList..sigGenes."]),] 
 write.table(exportData,file = filename,sep = "\t",quote = F,row.names = F)
} 


fisherSetTest <- function(geneLists,universe,sets,geneSymbols = NULL,p.value = 0.01){
 pValues <- vector("numeric",length = length(names(sets)))
 names(pValues) <- names(sets)
 
 for (set in names(sets)){
  counts <- matrix(c(length(intersect(sets[[set]],geneLists)),length(geneLists),length(intersect(sets[[set]],universe)),length(universe)),2,2)
  testResult <- fisher.test(counts,alternative = "greater")
  pValues[set] <- testResult$p.value
 }
 
 pAdj <- p.adjust(pValues,method = "fdr")
  
 report <- matrix(0,nrow = sum(pAdj < p.value),ncol = 3)
 sigGenes <- vector("character",length = sum(pAdj < p.value))
 rownames(report) <- names(pValues)[pAdj < p.value]
 names(sigGenes) <- rownames(report)
 print(rownames(report))
  
  for (set in rownames(report)){
   sigIDs <- intersect(sets[[set]],geneLists)
   report[set,1] <- length(sigIDs)
   sigGenes[set] <- paste(unlist(geneSymbols)[sigIDs],collapse = ",")
   report[set,2] <- length(intersect(sets[[set]],universe))
  } 
 report[,3] <- pAdj[pAdj < p.value] 
 report <- list(genesNumbers = report,geneSymbols = sigGenes) 
 report <- as.data.frame(report)
 
 return(report)
}

rawGenePlots <- function(geneLists,M,eGOnData,cols){
xx <- eGOnData
x11()
layout(matrix(c(1,2,3,4,5,6,7,8,9),3,3))
plotInd <- 0

lists <- names(geneLists)
 for(geneList in names(geneLists)){  
  for (viewgene in geneLists[[geneList]]){
    plotInd <- plotInd + 1
    plot(M[viewgene,],col = cols,main = paste(viewgene,xx[[viewgene]]),pch = 19)#,ylim = c(0,16))      
     
    if(plotInd == 9){
     savepng(fn = viewgene)
     x11()
     layout(matrix(c(1,2,3,4,5,6,7,8,9),3,3))
     plotInd <- 0
    }
  }
 } 
  
}





filterList <- function(listData,minGenes,maxGenes){
 listLengths <- lapply(listData,length)
 filteredList <- vector("list",length = sum(unlist(listLengths) >= minGenes & unlist(listLengths) <= maxGenes))
 names(filteredList) <- names(listLengths)[unlist(listLengths) >= minGenes & unlist(listLengths) <= maxGenes]

 for (set in names(filteredList)){
  filteredList[[set]] <- listData[[set]]
 } 
return(filteredList)
}



filterSets <- function(sets,M,minGenes,maxGenes){
 setLengths <- lapply(sets,length)
 
 for(set in names(sets)){
  setLengths[set] <- length(intersect(sets[[set]],rownames(M)))
 }


filteredSets <- vector("list",length = sum(unlist(setLengths) >= minGenes & unlist(setLengths) <= maxGenes))
 names(filteredSets) <- names(setLengths)[unlist(setLengths) >= minGenes & unlist(setLengths) <= maxGenes]
 
 for (set in names(filteredSets)){
  filteredSets[[set]] <- sets[[set]]
 } 
return(filteredSets)
}


mergeOnSymbol<- function(M,symbolList){
 #Handle NA
 naInd <- names(unlist(symbolList))[is.na(unlist(symbolList))]
 naInd <- intersect(naInd,rownames(M))
 #print(naInd)
 #unInd <- setdiff(rownames(M),names(symbolList))
 geneSymbols <- unique(unlist(symbolList))
 geneSymbols <- geneSymbols[!is.na(geneSymbols)]
 
 Mmerged <- matrix(0,nrow = length(naInd) + length(geneSymbols),ncol = dim(M)[2])
 rownames(Mmerged) <- as.character(1:dim(Mmerged)[1])
 rownames(Mmerged)[1:length(naInd)] <- naInd
 Mmerged[naInd,] <- M[naInd,]
 colnames(Mmerged) <- colnames(M)
 
 usedProbeIDs <- as.character((length(naInd)+1):dim(Mmerged)[1]) 
 names(usedProbeIDs) <- geneSymbols
 
 #rownames(Mmerged)[length(naInd) +1 :length(naInd) + length(unInd)] <- rownames(M)[unInd]
 rownames(Mmerged)[(length(naInd) + 1):dim(Mmerged)[1]] <- geneSymbols
 symbolList <- unlist(symbolList)
 symbolList <- symbolList[!is.na(symbolList)]
 
 
 for (geneSymbol in geneSymbols){
  probeIDs <- names(symbolList)[symbolList == geneSymbol]
  probeIDs <- intersect(probeIDs,rownames(M))
  
  if(length(probeIDs) ==1 ){
   Mmerged[geneSymbol,] <- M[probeIDs,]
   usedProbeIDs[geneSymbol] <- probeIDs 
   }
  if(length(probeIDs) > 1 ){
   probeID <- probeIDs[which.max(apply(M[probeIDs,],1,var))]
   Mmerged[geneSymbol,] <- M[probeID,]
   usedProbeIDs[geneSymbol] <- probeID
  }  
 }
print(length(usedProbeIDs))
print(length(naInd) +1)
print(dim(Mmerged)[1])
rownames(Mmerged)[(length(naInd) +1) :dim(Mmerged)[1]] <- usedProbeIDs
geneVars <- apply(Mmerged,1,var)
Mmerged <- Mmerged[geneVars !=0,]
print(length(naInd))
return(Mmerged)  
}




mergeOnGeneID <- function(M, geneIdList){
    ## M : ExpressionSet
    ## symbolList : genechip annotation
    symbols <- unlist(geneIdList)
    naInd <- names(symbols)[is.na(symbols)]
    naInd <- intersect(naInd, rownames(M))
 
    geneSymbols <- unique(symbols)
    geneSymbols <- geneSymbols[!is.na(geneSymbols)]
    
    Mmerged <- matrix(0, nrow = length(naInd) + length(geneSymbols),ncol = dim(M)[2])
    rownames(Mmerged) <- as.character(1 : dim(Mmerged)[1])
    rownames(Mmerged)[1 : length(naInd)] <- naInd
    Mmerged[naInd, ] <- M[naInd, ]
    colnames(Mmerged) <- colnames(M)
    
    usedProbeIDs <- as.character((length(naInd)+1) : dim(Mmerged)[1]) 
    names(usedProbeIDs) <- geneSymbols
 
    rownames(Mmerged)[(length(naInd) + 1) : dim(Mmerged)[1]] <- geneSymbols
    symbolList <- unlist(symbolList)
    symbolList <- symbolList[!is.na(symbolList)]
 
    for (geneSymbol in geneSymbols){
      probeIDs <- names(symbolList)[symbolList == geneSymbol]
      probeIDs <- intersect(probeIDs, rownames(M))
  
    if(length(probeIDs) == 1 ){
      Mmerged[geneSymbol,] <- M[probeIDs, ]
      usedProbeIDs[geneSymbol] <- probeIDs 
      }

    if(length(probeIDs) > 1 ){
      probeID <- probeIDs[which.max(apply(M[probeIDs,], 1, var))]
      Mmerged[geneSymbol, ] <- M[probeID, ]
      usedProbeIDs[geneSymbol] <- probeID
      }  
    }

    print( length(usedProbeIDs) )
    print( length(naInd) + 1 )
    print( dim(Mmerged)[1] )
    rownames(Mmerged)[(length(naInd) + 1) : dim(Mmerged)[1]] <- usedProbeIDs
    return(Mmerged)  
}  
 
